package xhwl.insurance.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lidroid.xutils.exception.DbException;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.android.common.log.XHLog;
import xhwl.android.common.util.IdcardValidator;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.BaseActivity;
import xhwl.insurance.Constant;
import xhwl.insurance.R;
import xhwl.insurance.customView.ChineseEditText;
import xhwl.insurance.customView.PopSelectPic;
import xhwl.insurance.db.SaleInfoDao;
import xhwl.insurance.db.SalePicInfoDao;
import xhwl.insurance.db.bean.SaleInfo;
import xhwl.insurance.db.bean.SalePicInfo;
import xhwl.insurance.dialog.LoadingDialog;
import xhwl.insurance.dialog.SubmitFailureDialog;
import xhwl.insurance.http.api.SubmitFileApi;
import xhwl.insurance.http.api.UploadPicApi;
import xhwl.insurance.http.bean.ImageEvent;
import xhwl.insurance.http.bean.ImageItem;
import xhwl.insurance.http.bean.ReferralPicBean;
import xhwl.insurance.http.bean.resp.ErrorCode;
import xhwl.insurance.util.AppUtil;
import xhwl.insurance.util.ImageDisplayer;
import xhwl.insurance.util.IntentConstants;
import xhwl.insurance.util.NumberJudgeUtils;
import xhwl.insurance.util.PermisionUtils;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;


public class SubmitCachedSaleInfoActivity extends BaseActivity implements OnClickListener, PopSelectPic.PopSelectBtnClickListener {
    private static final String TAG = SubmitCachedSaleInfoActivity.class.getSimpleName();
    public static final String EXTRA_DATA = "recordId";
    private String person_sex;
    int Year;
    EditText phone;
    private ChineseEditText name1;
    private EditText name;
    EditText number;
    Button submit;
    LinearLayout addPaitenetLayout;
    TextView tvDesc;
    EditText card_num;

//    private static String[] PERMISSION = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private String path;
    private File file1, file2, file3;
    private ImageView id_front, id_back, hmo_pic;
    private int flag;
    private static final int TAKE_PICTURE = 0x000000;
    private TextView card_name;

    int recordId;
    SaleInfo saleInfo;
    SaleInfoDao saleInfoDao;
    SalePicInfoDao salePicInfoDao;
    boolean autoSubmit;//是否自动提交
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {//上传图片结果回调
                //此时图片全部处理完成，有可能全部成功或部分成功
                if (autoSubmit) {//点击提交按钮在前，图片上传完成在后
                    updateDialogMsg();
                    SalePicInfo.UploadStatus uploadStatus = checkPicStatus();
                    if (SalePicInfo.UploadStatus.START != uploadStatus) {
                        //当前有上传中的图片，继续等待
                        dismissDialog();
                        updateFiles();
                    }
                }
            }
        }
    };
    private SalePicInfo idFront;
    private SalePicInfo idBack;
    private SalePicInfo hmoFront;

    private void cacheData(int status) {
        long updateTime = System.currentTimeMillis();

        saleInfo.person_name = name.getText().toString();
        saleInfo.person_mobile = phone.getText().toString();
        saleInfo.id_card_number = number.getText().toString();
        saleInfo.card_number = card_num.getText().toString();

        saleInfo.update_time = updateTime;
        saleInfo.status = status;
        try {
            saleInfoDao.update(saleInfo);
            Collection<SalePicInfo> list = saleInfo.picInfoMap.values();
            for (SalePicInfo info : list) {
                info.update_time = updateTime;
                salePicInfoDao.update(info);
            }
            Log.e("saleInfo", saleInfo.toString());
        } catch (DbException e) {
            e.printStackTrace();
        }

    }

    private void showFailDialog() {
        final SubmitFailureDialog pd = new SubmitFailureDialog(SubmitCachedSaleInfoActivity.this);
        pd.setCancelable(false);
        pd.setCanceledOnTouchOutside(false);
        if (!SubmitCachedSaleInfoActivity.this.isFinishing()) {
            pd.show();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    pd.dismiss();
                    AppUtil.startDealListPage(mContext, 4);
                    finish();
                }
            }, 2000);

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        saleInfoDao = new SaleInfoDao(mContext);
        salePicInfoDao = new SalePicInfoDao(mContext);
        recordId = getIntent().getIntExtra(EXTRA_DATA, 0);
        setContentView(R.layout.activity_update_sale_info);
        EventBus.getDefault().register(this);
    }

    @Override
    public void initViews() {
        initTitleViews();
        addPaitenetLayout = (LinearLayout) findViewById(R.id.addpaitenetlayout);
        name1 = (ChineseEditText) findViewById(R.id.add_paitent_name);
        name = (EditText) findViewById(R.id.add_paitent_name1);
        number = (EditText) findViewById(R.id.add_paitent_number);
        phone = (EditText) findViewById(R.id.add_paitent_phone);
        card_name = (TextView) findViewById(R.id.card_name);
        submit = (Button) findViewById(R.id.submit);
        tvDesc = (TextView) findViewById(R.id.tvDesc);
        card_num = (EditText) findViewById(R.id.card_num);
        id_front = (ImageView) findViewById(R.id.id_front);
        id_back = (ImageView) findViewById(R.id.id_back);
        hmo_pic = (ImageView) findViewById(R.id.hmo_pic);

        name1.setVisibility(View.GONE);
        name.setVisibility(View.VISIBLE);
        name.setEnabled(false);
        number.setEnabled(false);
        phone.setEnabled(false);
        card_num.setEnabled(false);



        name.clearFocus();
        number.clearFocus();
        phone.clearFocus();
        card_num.clearFocus();

        submit.setText("重新提交");
//        tvDesc.setText("(* 号为必填项)");
//        tvDesc.setTextColor(Color.RED);
        initRuleText();

    }

    private void initRuleText() {
        SpannableString jkcn = new SpannableString("400-656-2020");
        jkcn.setSpan(new ClickableSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                // TODO Auto-generated method stub
                super.updateDrawState(ds);
                ds.setColor(getResources().getColor(R.color.red));
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {
                // TODO Auto-generated method stub
                AppUtil.call(mContext, Constant.CUSTOMER_SERVE_PHONE);
            }
        }, 0, jkcn.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvDesc.setHighlightColor(Color.TRANSPARENT);
        tvDesc.append("提示：提交信息后，10分钟内可以修改信息，超过10分钟后请与客服人员联系 ");
        tvDesc.append(jkcn);
        // tvRule.append(jkcn);
        tvDesc.setMovementMethod(LinkMovementMethod.getInstance());
    }

    //    public void getSaleInfo() {
//        SaleInfoApi api = new SaleInfoApi();
//        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<SaleInfoResp>() {
//            @Override
//            public void onNext(SaleInfoResp resp) {
//                sale_userid = resp.user_id;
//                sale_mobile = resp.link_mobile;
//                getCardInfo();
//            }
//
//            @Override
//            public void onError(HttpException ex) {
//                super.onError(ex);
//                ToastUtil.showToast(mContext,"销售人信息不能为空，请重新请求网络");
//            }
//        });
//    }
//    void getCardInfo() {
//        String saleType=saleInfo.sale_type;
//        CardInfoApi api = new CardInfoApi(saleType);
//        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<CardInfo>() {
//            @Override
//            public void onNext(CardInfo resp) {
//                cardPrice = resp.card_money;
//                cardName = resp.card_name;
//                card_name.setText(cardName);
//            }
//
//            @Override
//            public void onError(HttpException ex) {
//                super.onError(ex);
//                ToastUtil.showToast(mContext,"卡信息不能为空，请重新请求网络");
//            }
//        });
//    }
    @Override
    public void initListener() {
        // TODO Auto-generated method stub
        submit.setOnClickListener(this);
        id_front.setOnClickListener(this);
        id_back.setOnClickListener(this);
        hmo_pic.setOnClickListener(this);
        number.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                if (s.length() == 18) {
                    String idNumber = s.toString();
                    String returnMsg = IdcardValidator.validate18Idcard(idNumber);
                    if (StringUtil.isEmpty(returnMsg)) {
                        try {
                            String strYear = idNumber.substring(6, 10);// 年份
                            String strMonth = idNumber.substring(10, 12);// 月份
                            String strDay = idNumber.substring(12, 14);// 月份
//                            date.setText(strYear + "-" + strMonth + "-" + strDay);
                            Year = Integer.parseInt(strYear);
                            String sexStr = idNumber.substring(15, 17);
                            int sex = Integer.parseInt(sexStr);
                            if (sex % 2 == 0) {
                                person_sex = "1";
                            } else {
                                person_sex = "0";
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            ToastUtil.showToast(mContext, e.getMessage());
                        }
                    } else {
                        ToastUtil.showToast(mContext, returnMsg);
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 11 && !NumberJudgeUtils.isMobileNO(phone.getText().toString())) {
                    ToastUtil.showToast(mContext, "手机号格式错误，请输入正确的手机号");
                }
            }
        });
    }

    @Override
    protected void setUpTitleView() {
        // TODO Auto-generated method stub
        super.setUpTitleView();
        titleTextView.setText("提交失败");

    }

    @Override
    protected void processOper() {
        // TODO Auto-generated method stub
        initData();

    }

    private void initData() {
        if (recordId == 0) {
            //新数据
            this.saleInfo = new SaleInfo();
        } else {

            try {
                this.saleInfo = saleInfoDao.findById(recordId);
                this.saleInfo.picInfoMap = new HashMap<>();
                List<SalePicInfo> list = salePicInfoDao.getListBySaleId(saleInfo.id);
                if (list != null && list.size() > 0) {
                    for (SalePicInfo info : list) {
                        this.saleInfo.picInfoMap.put(info.pic_type, info);
                    }
                }
                initViewData(saleInfo);
            } catch (DbException e) {
                this.saleInfo = new SaleInfo();
                e.printStackTrace();
            }
        }

    }

    private void initViewData(SaleInfo data) {
        xhwl.insurance.util.XHLog.i(data.toString());

        if (!StringUtil.isEmpty(data.person_name)) {
            name.setText(data.person_name);
        }
        if (!StringUtil.isEmpty(data.person_mobile)) {
            phone.setText(data.person_mobile);
        }
        if (!StringUtil.isEmpty(data.id_card_number)) {
            number.setText(data.id_card_number);
        }
        if (!StringUtil.isEmpty(data.card_name)) {
            card_name.setText(data.card_name);
        }
        if (!StringUtil.isEmpty(data.card_number)) {
            card_num.setText(data.card_number);
        }
        idFront = data.picInfoMap.get(SalePicInfo.PicType.ID_CARD_FORNT.ordinal());
        if (idFront != null && !StringUtil.isEmpty(idFront.save_path)) {
            file1 = new File(idFront.save_path);
            if (!file1.exists()) {
                file1 = null;
            }
            Glide.with(mContext)//加载本地图片
                    .load(idFront.save_path)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .error(R.drawable.pic_add)
                    .into(id_front);
        }
        idBack = data.picInfoMap.get(SalePicInfo.PicType.ID_CARD_BACK.ordinal());
        if (idBack != null && !StringUtil.isEmpty(idBack.save_path)) {
            file2 = new File(idBack.save_path);
            if (!file2.exists()) {
                file2 = null;
            }
            Glide.with(mContext)
                    .load(idBack.save_path)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .error(R.drawable.pic_add)
                    .into(id_back);
        }
        hmoFront = data.picInfoMap.get(SalePicInfo.PicType.HMO_CARD_FORNT.ordinal());
        if (hmoFront != null && !StringUtil.isEmpty(hmoFront.save_path)) {
            file3 = new File(hmoFront.save_path);
            if (!file3.exists()) {
                file3 = null;
            }
            Glide.with(mContext)
                    .load(hmoFront.save_path)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .error(R.drawable.pic_add)
                    .into(hmo_pic);
        }
//        name.setSelection(name.getText().length());
//        name.requestFocus();
    }

    @Override
    public void loadData() {
        // TODO Auto-generated method stub
//        getSaleInfo();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_front:
//                flag = 1;
//                PopSelectPic popfront = new PopSelectPic(this, id_front);
//                popfront.setCallBack(this);
                Intent intent = new Intent(this, PictureSlideActivity.class);
                intent.putExtra("imgshow", idFront.save_path);
                intent.putExtra("imgshow2", idBack.save_path);
                intent.putExtra("imgshow3", hmoFront.save_path);
                intent.putExtra("type", "1");
                startActivity(intent);
                break;
            case R.id.id_back:
//                flag = 2;
//                PopSelectPic popback = new PopSelectPic(this, id_back);
//                popback.setCallBack(this);
                Intent intent2 = new Intent(this, PictureSlideActivity.class);
                intent2.putExtra("imgshow", idFront.save_path);
                intent2.putExtra("imgshow2", idBack.save_path);
                intent2.putExtra("imgshow3", hmoFront.save_path);
                intent2.putExtra("type", "2");
                startActivity(intent2);
                break;
            case R.id.hmo_pic:
//                flag = 3;
//                PopSelectPic pophmo = new PopSelectPic(this, id_back);
//                pophmo.setCallBack(this);
                Intent intent3 = new Intent(this, PictureSlideActivity.class);
                intent3.putExtra("imgshow", idFront.save_path);
                intent3.putExtra("imgshow2", idBack.save_path);
                intent3.putExtra("imgshow3", hmoFront.save_path);
                intent3.putExtra("type", "3");
                startActivity(intent3);
                break;
            case R.id.submit://添加被保障人
                if (vilidInput()) {
//                    submit.setEnabled(false);
                    SalePicInfo.UploadStatus uploadStatus = checkPicStatus();
                    if (SalePicInfo.UploadStatus.SUCCESS == uploadStatus) {//图片全部上传完成
                        updateFiles();
                    } else {
                        //有图片正在上传
                        autoSubmit = true;//等待
                        showDialog();
                        //有上传失败的情况
                        if (SalePicInfo.UploadStatus.FAIL == uploadStatus) {
                            Collection<SalePicInfo> values = saleInfo.picInfoMap.values();
                            List<File> failList = new ArrayList<>();
                            for (SalePicInfo info : values) {
                                if (info.status == SalePicInfo.UploadStatus.FAIL.ordinal()) {
                                    if (info.pic_type == SalePicInfo.PicType.ID_CARD_FORNT.ordinal()) {
                                        failList.add(file1);
                                    } else if (info.pic_type == SalePicInfo.PicType.ID_CARD_BACK.ordinal()) {
                                        failList.add(file2);
                                    } else if (info.pic_type == SalePicInfo.PicType.HMO_CARD_FORNT.ordinal()) {
                                        failList.add(file3);
                                    }
                                }
                            }
                            uploadPic(failList);
                        }
                    }
                }
                break;
            default:
                break;
        }
    }

    private String getCountMsg() {
        int successCount = 0;
        Collection<SalePicInfo> values = saleInfo.picInfoMap.values();
        for (SalePicInfo info : values) {
            if (SalePicInfo.UploadStatus.SUCCESS.ordinal() == info.status) {
                successCount++;
            }
        }
        if (successCount == 0) {
            return "请稍候...";
        }
        return "请稍候" + successCount + "/" + values.size();
    }

    LoadingDialog dialog;

    private void showDialog() {

        dialog = new LoadingDialog(mContext, getCountMsg());
//        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                autoSubmit = false;//等待上传图片过程中，用户取消对话框以后，不再继续提交，用户可以再次点提交按钮
            }
        });
        dialog.show();
    }

    private void updateDialogMsg() {
        if (dialog != null && dialog.isShowing()) {
            dialog.setText(getCountMsg());
        }
    }

    private void dismissDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    private SalePicInfo.UploadStatus checkPicStatus() {
        xhwl.insurance.util.XHLog.e(saleInfo.picInfoMap.toString());
        Collection<SalePicInfo> values = saleInfo.picInfoMap.values();
        int successCount = 0;
        boolean isUploading = false;
        for (SalePicInfo info : values) {
            if (SalePicInfo.UploadStatus.START.ordinal() == info.status) {
                isUploading = true;
            } else if (SalePicInfo.UploadStatus.SUCCESS.ordinal() == info.status) {
                successCount++;
            }
        }

        if (isUploading) {
            return SalePicInfo.UploadStatus.START;
        }
        if (successCount == values.size()) {
            return SalePicInfo.UploadStatus.SUCCESS;
        } else {
            return SalePicInfo.UploadStatus.FAIL;
        }
    }

    private int getPicType(File file) {
        if (file == file1) {
            return SalePicInfo.PicType.ID_CARD_FORNT.ordinal();
        } else if (file == file2) {
            return SalePicInfo.PicType.ID_CARD_BACK.ordinal();
        } else if (file == file3) {
            return SalePicInfo.PicType.HMO_CARD_FORNT.ordinal();
        }
        throw new IllegalArgumentException("参数异常");
    }

    private void uploadPic(final List<File> fileList) {
        if (fileList == null || fileList.size() == 0)
            return;
        for (File file : fileList) {
            Integer type = getPicType(file);
            SalePicInfo salePicInfo = saleInfo.picInfoMap.get(type);
            if (salePicInfo == null) {//正常情况不会执行此代码
                salePicInfo = new SalePicInfo();
                saleInfo.picInfoMap.put(type, salePicInfo);
            }
        }
        final UploadPicApi api = new UploadPicApi(mContext, false, fileList.toArray(new File[fileList.size()]));
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {
            @Override
            public void onStart() {
                super.onStart();
                for (File file : fileList) {
                    Integer type = getPicType(file);
                    SalePicInfo picInfo = saleInfo.picInfoMap.get(type);
                    picInfo.pic_type = type;
                    picInfo.status = SalePicInfo.UploadStatus.START.ordinal();
                    picInfo.save_path = file.getPath();
                    picInfo.url = "";
                }
            }

            @Override
            public void onNext(ArrayList<ReferralPicBean> picBeanList) {
                for (int i = 0; i < fileList.size(); i++) {
                    Integer type = getPicType(fileList.get(i));
                    SalePicInfo picInfo = saleInfo.picInfoMap.get(type);
                    picInfo.url = picBeanList.get(i).getUrl_big();
                    picInfo.status = SalePicInfo.UploadStatus.SUCCESS.ordinal();
                }
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                for (File file : fileList) {
                    Integer type = getPicType(file);
                    SalePicInfo picInfo = saleInfo.picInfoMap.get(type);
                    picInfo.status = SalePicInfo.UploadStatus.FAIL.ordinal();
                }
                handler.sendEmptyMessage(0);
            }
        });
    }

    private void uploadPic(final File file) {
        if (file == null)
            return;
        final Integer type = getPicType(file);
        SalePicInfo salePicInfo = saleInfo.picInfoMap.get(type);
        if (salePicInfo == null) {//正常情况不会执行此代码
            salePicInfo = new SalePicInfo();
            saleInfo.picInfoMap.put(type, salePicInfo);
        }
        final SalePicInfo picInfo = saleInfo.picInfoMap.get(type);

        final UploadPicApi api = new UploadPicApi(mContext, false, new File[]{file});
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {
            @Override
            public void onStart() {
                super.onStart();

                picInfo.pic_type = type;
                picInfo.status = SalePicInfo.UploadStatus.START.ordinal();
                picInfo.save_path = file.getPath();
                picInfo.url = "";
            }

            @Override
            public void onNext(ArrayList<ReferralPicBean> picBeanList) {
                picInfo.url = picBeanList.get(0).getUrl_big();
                picInfo.status = SalePicInfo.UploadStatus.SUCCESS.ordinal();
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                picInfo.status = SalePicInfo.UploadStatus.FAIL.ordinal();
                handler.sendEmptyMessage(0);
            }
        });
    }


    private void updateFiles() {

        SalePicInfo.UploadStatus uploadStatus = checkPicStatus();
        if (SalePicInfo.UploadStatus.SUCCESS != uploadStatus) {//图片没有全部上传完成
            cacheData(SaleInfo.Status.FAIL.ordinal());
//            showFailDialog();
            ToastUtil.showToast(mContext, "请求超时，请检查当前网络");
            return;
        }
        String card_front = saleInfo.picInfoMap.get(SalePicInfo.PicType.ID_CARD_FORNT.ordinal()).url;
        String card_back = saleInfo.picInfoMap.get(SalePicInfo.PicType.ID_CARD_BACK.ordinal()).url;
        String card_number_pic = saleInfo.picInfoMap.get(SalePicInfo.PicType.HMO_CARD_FORNT.ordinal()).url;


        int currentYear = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date(System.currentTimeMillis())));
        String age = String.valueOf(currentYear - Year);
        String sale_date = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
        final SubmitFileApi api = new SubmitFileApi(saleInfo.c_type, age, number.getText().toString(), phone.getText().toString(),
                name.getText().toString(), person_sex, saleInfo.saler_mobile, saleInfo.sale_type, saleInfo.saler_user_id,
                saleInfo.yw_id, card_num.getText().toString(), card_number_pic,
                saleInfo.card_price, card_front, card_back, sale_date);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ErrorCode>() {
            @Override
            public void onNext(ErrorCode resp) {
                if (resp.getError_code().equals("ok")) {
                    ToastUtil.showToast(mContext, "提交资料成功");
                    cacheData(SaleInfo.Status.SUCCESS.ordinal());
                    AppUtil.startDealListPage(mContext, 1);
                    finish();

                } else {
                    if ("00046".equals(resp.getError_code())) {
                        ToastUtil.showToast(mContext, "卡号不存在或卡已被绑定");
                    } else if ("00048".equals(resp.getError_code())) {
                        ToastUtil.showToast(mContext, "该卡为预售不可退，您无权限绑定");
                    } else if ("00049".equals(resp.getError_code())) {
                        ToastUtil.showToast(mContext, "该套装的卡号不存在或已绑定");
                    } else {
                        ToastUtil.showToast(mContext, "提交资料失败,请重新点击提交");
                    }
                }
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                cacheData(SaleInfo.Status.FAIL.ordinal());
//                showFailDialog();
                ToastUtil.showToast(mContext, ex.getMessage());

            }
        });

    }

    public Boolean vilidInput() {
        String msg = "";
        if (TextUtils.isEmpty(name.getText())) {
            msg = "姓名输入不能为空";
        } else if (TextUtils.isEmpty(phone.getText())) {
            msg = "手机号输入不能为空";
        } else if (phone.getText().toString().length() != 11) {
            msg = "手机号为11位数字，请输入正确的手机号";
        } else if (false == NumberJudgeUtils.isMobileNO(phone.getText().toString())) {
            msg = "手机号格式错误，请输入正确的手机号";
        } else if (StringUtil.isEmpty(number.getText().toString())) {
            msg = "身份证号码不能为空";
        } else if (!StringUtil.isEmpty(IdcardValidator.validate18Idcard(number.getText().toString()))) {
            msg = IdcardValidator.validate18Idcard(number.getText().toString());
        } else if (StringUtil.isEmpty(card_num.getText().toString())) {
            msg = "HMO卡卡号不能为空";
        } else if (null == file1 || "".equals(file1.getPath())) {
            msg = "身份证正面照片不能为空，请上传身份证正面照片";
        } else if (null == file2 || "".equals(file2.getPath())) {
            msg = "身份证背面照片不能为空，请上传身份证背面照片";
        } else if (null == file3 || "".equals(file3.getPath())) {
            msg = "卡号照片不能为空，请上传卡号照片";
        } else if (StringUtil.isEmpty(saleInfo.saler_user_id) || StringUtil.isEmpty(saleInfo.saler_mobile)) {
//            msg="销售人信息不能为空，请重新请求网络";
            msg = "请求超时，请重新请求网络";
        }
        if (TextUtils.isEmpty(msg)) {
            return true;
        } else {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    @Override
    public void onTakePhotoClick() {
        takePhoto();
    }

    @Override
    public void onSelectPicClick() {
        pickPicture();
    }

    private void pickPicture() {
//        if (PermisionUtils.islacksOfPermission(this, PERMISSION[1])) {
//            ToastUtil.showToast(this, "请打开提示对应权限,否则将无法选择您的照片");
//            ActivityCompat.requestPermissions(this, PERMISSION, 1);
//        } else {
//            Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
//            intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
//            startActivity(intent);
//        }
        //2017.11.21权限替换 后期测试没有问题删除注释liujin
        requestPermission();
    }

    private void requestPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
                    intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, 1);
                    startActivity(intent);
                } else {
                    Log.e(TAG, "用户拒绝开启权限");
                    PermisionUtils.dialog(SubmitCachedSaleInfoActivity.this, "用户拒绝开启权限");
                }
            }
        });


    }


    public void takePhoto() {
//        if (PermisionUtils.islacksOfPermission(SubmitCachedSaleInfoActivity.this, PERMISSION[0])) {
//            ToastUtil.showToast(this, "请打开提示对应权限,否则将影响拍照功能无法使用");
//            ActivityCompat.requestPermissions(this, PERMISSION, 0);
//        } else {
//            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//
//            File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
//            if (!vFile.exists()) {
//                File vDirPath = vFile.getParentFile();
//                vDirPath.mkdirs();
//            } else {
//                if (vFile.exists()) {
//                    vFile.delete();
//                }
//            }
//            path = vFile.getPath();
//            Uri cameraUri;
//            if (Build.VERSION.SDK_INT >= 24) {
//                cameraUri = FileProvider.getUriForFile(this.getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
//            } else {
//                cameraUri = Uri.fromFile(vFile);
//            }
//            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
//            startActivityForResult(openCameraIntent, TAKE_PICTURE);
//        }
        //2017.11.21权限替换 后期测试没有问题删除注释liujin
        requestTakePicPermission();
    }

    private void requestTakePicPermission() {
        new RxPermissions(this).request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Action1<Boolean>() {
            @Override
            public void call(Boolean granted) {
                if (granted) {
                    Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                    File vFile = new File(Environment.getExternalStorageDirectory() + "/myimage/", String.valueOf(System.currentTimeMillis()) + ".jpg");
                    if (!vFile.exists()) {
                        File vDirPath = vFile.getParentFile();
                        vDirPath.mkdirs();
                    } else {
                        if (vFile.exists()) {
                            vFile.delete();
                        }
                    }
                    path = vFile.getPath();
                    Uri cameraUri;
                    if (Build.VERSION.SDK_INT >= 24) {
                        cameraUri = FileProvider.getUriForFile(getApplicationContext(), "xhwl.insurance.fileProvider", vFile);
                    } else {
                        cameraUri = Uri.fromFile(vFile);
                    }
                    openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
                    startActivityForResult(openCameraIntent, TAKE_PICTURE);

                } else {
                    Log.e(TAG, "请打开提示对应权限,否则将影响拍照功能无法使用");
                    PermisionUtils.dialog(SubmitCachedSaleInfoActivity.this, "请打开提示对应权限,否则将影响拍照功能无法使用");
                }
            }
        });
    }

    public void onEvent(ImageEvent event) {
        if (event == null)
            return;

        Collection<ImageItem> collection = event.getCollection();

        for (ImageItem item : collection) {// 目前只能选择一张图片，可上传多张图片时，需根据接口定义修改s
            XHLog.e("sourcePath=" + item.getSourcePath());
            initImageFiles(item);
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {
            ImageItem item = new ImageItem();
            item.sourcePath = path;
            XHLog.e("sourcePath=" + item.sourcePath);
            initImageFiles(item);
        }
    }

    private void initImageFiles(ImageItem item) {
        String fileName = xhwl.insurance.util.BitmapUtil.handleImage(mContext, item.sourcePath, 200);
        if (flag == 1) {
            file1 = new File(fileName);
            ImageDisplayer.getInstance(mContext).displayBmp(id_front, item.thumbnailPath, item.sourcePath);
            uploadPic(file1);
        } else if (flag == 2) {
            file2 = new File(fileName);
            ImageDisplayer.getInstance(mContext).displayBmp(id_back, item.thumbnailPath, item.sourcePath);
            uploadPic(file2);
        } else if (flag == 3) {
            file3 = new File(fileName);
            ImageDisplayer.getInstance(mContext).displayBmp(hmo_pic, item.thumbnailPath, item.sourcePath);
            uploadPic(file3);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    takePhoto();
                } else {
                    ToastUtil.showToast(this, "请您打开本应用的拍照权限,否则将无法拍照");
                }
                break;
            case 1:
                if (grantResults.length > 0 && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    pickPicture();
                } else {
                    ToastUtil.showToast(this, "请您打开本应用的读取存储权限,否则将无法获取相册照片");
                }
                break;
        }
    }
}
